/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useRef, useState } from 'react'
import { Button, Card, Form, Input, message } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import './Login.scss'

export default function Login() {
  const [form] = Form.useForm()
  const navigate = useNavigate()
  const location = useLocation()

  // 简单图形验证码
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [realCode, setRealCode] = useState('')

  const makeCode = () => {
    const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
    let s = ''
    for (let i = 0; i < 4; i++) s += chars[Math.floor(Math.random() * chars.length)]
    return s
  }

  const draw = (text: string) => {
    const canvas = canvasRef.current
    if (!canvas) return
    const w = 100, h = 40
    canvas.width = w
    canvas.height = h
    const ctx = canvas.getContext('2d')!
    ctx.clearRect(0, 0, w, h)
    ctx.fillStyle = '#f3f5f7'
    ctx.fillRect(0, 0, w, h)
    ctx.font = '24px sans-serif'
    ctx.textBaseline = 'middle'
    for (let i = 0; i < text.length; i++) {
      const x = 15 + i * 20
      const y = h / 2 + (Math.random() * 8 - 4)
      ctx.fillStyle = `hsl(${Math.floor(Math.random() * 360)},70%,40%)`
      const ch = text[i]
      const angle = (Math.random() - 0.5) * 0.6
      ctx.save()
      ctx.translate(x, y)
      ctx.rotate(angle)
      ctx.fillText(ch, 0, 0)
      ctx.restore()
    }
    for (let i = 0; i < 3; i++) {
      ctx.strokeStyle = 'rgba(0,0,0,0.25)'
      ctx.beginPath()
      ctx.moveTo(Math.random() * w, Math.random() * h)
      ctx.lineTo(Math.random() * w, Math.random() * h)
      ctx.stroke()
    }
  }

  const refresh = () => {
    const code = makeCode().toUpperCase()
    setRealCode(code)
    draw(code)
    form.setFieldValue('_captcha_real', code)
  }

  useEffect(() => {
    refresh()
  }, [])

  const onFinish = (vals: any) => {
    const input = (vals.captcha || '').toString().trim().toUpperCase()
    const real = (vals._captcha_real || realCode).toString().trim().toUpperCase()
    if (!input) { message.error('请输入验证码'); return }
    if (input !== real) { message.error('验证码错误，请重试'); refresh(); return }
    // 模拟登录成功：存 token 与用户名
    localStorage.setItem('token', Math.random().toString(36).slice(2))
    if (vals.username) localStorage.setItem('username', vals.username)
    message.success('登录成功')
    const target = (location.state as any)?.from || '/index/home'
    navigate(target, { replace: true })
  }

  return (
    <div className="login-page">
      <Card className="login-card" variant="outlined">
        <div className="login-title-cn">仓储管理系统</div>
        <div className="login-title-en">Warehouse Management System</div>
        <Form form={form} layout="vertical" onFinish={onFinish}>
          <Form.Item name="username" rules={[{ required: true, message: '请输入用户名' }]}>
            <Input placeholder="请输入用户名" />
          </Form.Item>
          <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
            <Input.Password placeholder="请输入密码" />
          </Form.Item>

          {/* 验证码：放在密码框下面 */}
          <Form.Item name="_captcha_real" hidden>
            <Input />
          </Form.Item>
          <Form.Item style={{ marginTop: 8 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <Form.Item name="captcha" noStyle rules={[{ required: true, message: '请输入验证码' }]}>
                <Input placeholder="请输入校验码" maxLength={4} style={{ flex: 1 }} />
              </Form.Item>
              <canvas
                ref={canvasRef}
                onClick={refresh}
                className="captcha-canvas"
                style={{ width: 100, height: 40, cursor: 'pointer' }}
              />
              <Button type="link" onClick={refresh} style={{ padding: 0 }}>换一张</Button>
            </div>
          </Form.Item>

          <Button type="primary" htmlType="submit" block>
            登录
          </Button>
        </Form>
      </Card>
    </div>
  )
}
